package com.example.peibei.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.dingtao.common.bean.Dynamic;
import com.dingtao.common.bean.GetOrder;
import com.dingtao.common.bean.RefreshResult;
import com.dingtao.common.bean.GetComment;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.DateUtils;
import com.dingtao.common.util.GlideUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.CommentFollowPresenter;
import com.example.peibei.service.presenter.DeleteDynamicPresenter;
import com.example.peibei.service.presenter.DynamicComPresenter;
import com.example.peibei.service.presenter.FollowPresenter;
import com.example.peibei.service.presenter.FollowUserPresenter;
import com.example.peibei.service.presenter.GetComentListPresenter;
import com.example.peibei.service.presenter.GiveUpPresenter;
import com.example.peibei.ui.utils.SoftKeyBoardListener;
import com.example.peibei.ui.weight.CenterDialog;
import com.linxiao.framework.common.DateUtil;
import com.linxiao.framework.dialog.BottomDialog;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.dingtao.common.util.DateUtils.DATE_PATTERN;
import static com.dingtao.common.util.UIUtils.dp2px;

public class DynamicDetailActivity extends WDActivity {
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.ll_imgs)
    LinearLayout ll_imgs;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.iv_img_one)
    ImageView imgOne;
    @BindView(R.id.iv_img_two)
    ImageView imgTwo;
    @BindView(R.id.iv_img_three)
    ImageView imgThree;
    @BindView(R.id.ll_no_follow)
    LinearLayout ll_no_follow;
    @BindView(R.id.ll_followed)
    LinearLayout ll_followed;
    @BindView(R.id.commentList)
    RecyclerView commentList;

    @BindView(R.id.zan)
    ImageView zan;
    @BindView(R.id.zan_tv)
    TextView zan_tv;
    @BindView(R.id.zan_ly)
    View zan_ly;
    @BindView(R.id.llContent)
    View llContent;
    @BindView(R.id.et_content)
    EditText mEtContent;
    @BindView(R.id.view_keybord)
    View view_keybord;
    @BindView(R.id.scroll_view)
    View scroll_view;
    @BindView(R.id.com_num)
    TextView com_num;
    @BindView(R.id.iv_delate)
    ImageView iv_delate;

    private SPUtils spUtils;
    private String token;
    private String status;
    private FollowPresenter followPresenter;
    private GiveUpPresenter giveUpPresenter;
    private FollowUserPresenter followUserPresenter;
    GetComentListPresenter comentListPresenter;
    Dynamic.RecordsDTO dynamic;
    List<GetComment> list = new ArrayList<>();
    QuickAdapter quickAdapter = new QuickAdapter();
    private InputMethodManager mInputManager;
    DynamicComPresenter dynamicComPresenter;
    private CommentFollowPresenter commentFollowPresenter;
    private DeleteDynamicPresenter deleteDynamicPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamic_detail;
    }

    @Override
    protected void initView() {
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        status = bundle.getString("status");
        dynamic = (Dynamic.RecordsDTO) bundle.getSerializable("dynamic");
        spUtils = new SPUtils(DynamicDetailActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        setOrderDetail(dynamic);
        deleteDynamicPresenter = new DeleteDynamicPresenter(new DeleteCall());
        followPresenter = new FollowPresenter(new FollowCall());
        giveUpPresenter = new GiveUpPresenter(new FollowCall());
        dynamicComPresenter = new DynamicComPresenter(new CommentCall());
        followUserPresenter = new FollowUserPresenter(new FollowUserCall());
        commentFollowPresenter = new CommentFollowPresenter(new DianzanCall());
        comentListPresenter = new GetComentListPresenter(new GetCommentListCall());
        ll_followed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                followUserPresenter.reqeust(0, "Bearer " + token, dynamic.getMid() + "");
                ll_followed.setVisibility(View.GONE);
                ll_no_follow.setVisibility(View.VISIBLE);

            }
        });
        ll_no_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                followUserPresenter.reqeust(1, "Bearer " + token, dynamic.getMid() + "");
                ll_followed.setVisibility(View.VISIBLE);
                ll_no_follow.setVisibility(View.GONE);
            }
        });
        zan_ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zan();
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        commentList.setLayoutManager(linearLayoutManager);
        commentList.setAdapter(quickAdapter);

        comentListPresenter.reqeust(true, "Bearer " + token, dynamic.getId());

        initEditHight();
        mEtContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {

                    dynamicComPresenter.reqeust("Bearer " + token, mEtContent.getText().toString(), String.valueOf(dynamic.getId()));
                    mEtContent.setText("");
                    mInputManager.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                    mEtContent.clearFocus();
                }
                return false;
            }
        });
        mEtContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    lockContentHeight();//显示软件盘时，锁定内容高度，防止跳闪。

                    showSoftInput();


                    //软件盘显示后，释放内容高度
                    mEtContent.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            unlockContentHeightDelayed();
                        }
                    }, 200L);
                }
                return false;
            }
        });
        //点击空白区域关闭键盘
        scroll_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mInputManager.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                mEtContent.clearFocus();
                return false;
            }
        });
    }

    public void showSoftInput() {
        mEtContent.requestFocus();
        mEtContent.post(new Runnable() {
            @Override
            public void run() {
                mInputManager.showSoftInput(mEtContent, 0);
            }
        });
    }

    /**
     * 锁定内容高度，防止跳闪
     */
    private void lockContentHeight() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) llContent.getLayoutParams();
        params.height = llContent.getHeight();
        params.weight = 0.0F;
    }

    /**
     * 释放被锁定的内容高度
     */
    public void unlockContentHeightDelayed() {
        mEtContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                ((LinearLayout.LayoutParams) llContent.getLayoutParams()).weight = 1.0F;
            }
        }, 200L);
    }

    /**
     * 使键盘能够弹起
     */
    private void initEditHight() {
        //监听软键盘弹出，并获取软键盘高度
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘弹起事件  并给View设置高度
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view_keybord.getLayoutParams();
                layoutParams.height = height;
                view_keybord.setLayoutParams(layoutParams);
            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘隐藏事件  并给View设置高度为0
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view_keybord.getLayoutParams();
                layoutParams.height = 0;
                view_keybord.setLayoutParams(layoutParams);
            }
        });

        quickAdapter.addChildClickViewIds(R.id.zan_ly);
        quickAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.zan_ly) {
                    GetComment.TDynamicComment item = (GetComment.TDynamicComment) adapter.getData().get(position);
                    int follow;
                    String id = item.getId();
                    boolean dianzan = item.isDianzan();
                    if (dianzan) {
                        follow = 0;
                    } else {
                        follow = 1;
                    }
                    commentFollowPresenter.reqeust(follow, "Bearer " + token, id);
//                    followPresenter.reqeust(follow, "Bearer " + token, id);
                } else if (view.getId() == R.id.iv_head) {
                    Dynamic.RecordsDTO order = (Dynamic.RecordsDTO) adapter.getData().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString("mid", order.getMember().getId() + "");
                    intent(PersonInfoActivityTwo.class, bundle);
                }
            }
        });
    }

    private void zan() {
        int follow = dynamic.getFollow();
        long id = dynamic.getId();
//        followPresenter.reqeust(follow, "Bearer " + token, id + "");
        giveUpPresenter.reqeust(follow, "Bearer " + token, id + "");
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.iv_delate)
    public void delateDynamic() {
        showDialog();
    }

    private void showDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_report, null);
        BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_lahei = dialogView.findViewById(R.id.tv_lahei);
        LinearLayout ll_copy = dialogView.findViewById(R.id.ll_copy);
        LinearLayout ll_jubao = dialogView.findViewById(R.id.ll_jubao);
        LinearLayout ll_lahei = dialogView.findViewById(R.id.ll_lahei);
        LinearLayout ll_delete = dialogView.findViewById(R.id.ll_delete);
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        ll_copy.setVisibility(View.GONE);
        ll_jubao.setVisibility(View.GONE);
        ll_lahei.setVisibility(View.GONE);
        ll_delete.setVisibility(View.VISIBLE);
        ll_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDeletelDialog();
                bottomDialog.dismiss();
            }
        });
    }

    private void showDeletelDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_center_view, null);
        CenterDialog bottomDialog = new CenterDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();

        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_sure = dialogView.findViewById(R.id.tv_sure);
        TextView tv_title = dialogView.findViewById(R.id.tv_title);
        tv_title.setText("确定删除此动态吗？");
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        tv_sure.setOnClickListener(v -> {
            deleteDynamicPresenter.reqeust("Bearer " + token, dynamic.getId() + "");
            bottomDialog.dismiss();
        });
    }

    private void setOrderDetail(Dynamic.RecordsDTO data) {
        tv_name.setText(data.getMember().getNickName());
        tv_address.setText("来自" + data.getMember().getArea());
        Glide.with(DynamicDetailActivity.this).load(data.getMember().getImgUrl()).into(iv_head);
        tv_content.setText(data.getTitle());
        if (status.equals("0")) {
            ll_no_follow.setVisibility(View.GONE);
            ll_followed.setVisibility(View.GONE);
            iv_delate.setVisibility(View.VISIBLE);
        } else {
            iv_delate.setVisibility(View.GONE);
            if (data.getFollow() == 0) {
                ll_no_follow.setVisibility(View.VISIBLE);
                ll_followed.setVisibility(View.GONE);
            } else {
                ll_no_follow.setVisibility(View.GONE);
                ll_followed.setVisibility(View.VISIBLE);
            }
        }
        List<Dynamic.RecordsDTO.ItemDTO> items = data.getItem();
        if (items.size() > 0) {
            ll_imgs.setVisibility(View.VISIBLE);
            if (items.get(0) != null && !items.get(0).getUrl().equals("")) {
//                Glide.with(this).load(items.get(0).getUrl()).into(imgOne);
//                RequestOptions transforms = new RequestOptions().transforms(new MultiTransformation(new FitCenter(), new RoundedCorners(dp2px(10f))));
//                Glide.with(this).load(items.get(0).getUrl()).apply(transforms).into(imgOne);
                GlideUtils.loadImgTwo(this, items.get(0).getUrl(), 20, imgOne);
            }
            if (items.size() > 1 && items.get(1) != null && !items.get(1).getUrl().equals("")) {
//                Glide.with(this).load(items.get(1)).into(imgTwo);
                GlideUtils.loadImgTwo(this, items.get(1).getUrl(), 20, imgTwo);
            }
            if (items.size() > 2 && items.get(2) != null && !items.get(2).getUrl().equals("")) {
//                Glide.with(this).load(items.get(2).getUrl()).into(imgThree);
                GlideUtils.loadImgTwo(this, items.get(2).getUrl(), 20, imgThree);
            }
        } else {
            ll_imgs.setVisibility(View.GONE);
        }
        Log.i("answer","点赞数量："+data.getCount()+"点赞："+data.getComment());
        if (data.getCount() > 0) {
            zan_tv.setText("点赞" + data.getCount());
        }
//        if (dynamic.getFollow() == 0) {
//            zan.setImageResource(R.drawable.zan_img);
//            zan_tv.setText("点赞");
//            zan_tv.setTextColor(Color.parseColor("#ff6a6b6e"));
//        } else {
//            zan.setImageResource(R.drawable.zan_yellow);
//            zan_tv.setText(String.valueOf(dynamic.getFollow()));
//            zan_tv.setTextColor(Color.parseColor("#F76307"));
//        }
        imgOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        imgTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    @Override
    protected void destoryData() {

    }

    class FollowCall implements DataCall<Dynamic> {

        @Override
        public void success(Dynamic data, Object... args) {
            //还需要刷新处理
            int follow = dynamic.getFollow();
            dynamic.setFollow(follow == 0 ? 1 : 0);
            if (dynamic.getFollow() == 0) {
                zan.setImageResource(R.mipmap.zan_img);
                zan_tv.setText("点赞");
                zan_tv.setTextColor(Color.parseColor("#ff6a6b6e"));
            } else {
                zan.setImageResource(R.mipmap.zan_yellow);
                zan_tv.setText(String.valueOf(dynamic.getFollow()));
                zan_tv.setTextColor(Color.parseColor("#F76307"));
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }

    class DeleteCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("删除成功");
            finish();
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class FollowUserCall implements DataCall<Dynamic> {

        @Override
        public void success(Dynamic data, Object... args) {
            //还需要刷新处理
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class DianzanCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            //还需要刷新处理
            comentListPresenter.reqeust(true, "Bearer " + token, dynamic.getId());
        }

        @Override
        public void fail(ApiException e, Object... args) {
//            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }


    class CommentCall implements DataCall<Dynamic> {

        @Override
        public void success(Dynamic data, Object... args) {
            //还需要刷新处理
            comentListPresenter.reqeust(true, "Bearer " + token, dynamic.getId());
            UIUtils.showToastSafe("评论成功");


        }

        @Override
        public void fail(ApiException e, Object... args) {
//            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }

    class GetCommentListCall implements DataCall<GetComment> {

        @Override
        public void success(GetComment data, Object... args) {
            //添加列表并刷新
            if (comentListPresenter.getPage() == 1) {
                list.clear();
            }
            quickAdapter.setNewInstance(data.getRecords());
            quickAdapter.notifyDataSetChanged();
            com_num.setText(String.valueOf(data.getTotal()));
        }

        @Override
        public void fail(ApiException e, Object... args) {
            Log.e("eeeeeee", e.toString());
        }
    }


    public class QuickAdapter extends BaseQuickAdapter<GetComment.TDynamicComment, BaseViewHolder> {

        public QuickAdapter() {
            super(R.layout.comment_list_item_layout);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, final GetComment.TDynamicComment item) {
            try {
                viewHolder.setText(R.id.commentMember, item.getCommentMember())
                        .setText(R.id.message, item.getMessage())
                        .setText(R.id.addTime, DateUtils.dateTransformer(Long.parseLong(item.getAddTime()), DATE_PATTERN));
            } catch (ParseException e) {
                e.printStackTrace();
            }


            View rply_ly = viewHolder.getView(R.id.rply_ly);
            if (TextUtils.isEmpty(item.getReply())) {
                rply_ly.setVisibility(View.GONE);
            } else {
                rply_ly.setVisibility(View.VISIBLE);
                viewHolder.setText(R.id.reply_name, item.getAddTime())
                        .setText(R.id.reply, item.getReply())
                        .setText(R.id.addTime, item.getAddTime());
            }
            ImageView head = viewHolder.getView(R.id.iv_head);
            ImageView iv_head_small = viewHolder.getView(R.id.iv_head_small);
            ImageView zan = viewHolder.getView(R.id.zan);
            TextView zan_tv = viewHolder.getView(R.id.zan_tv);
            Glide.with(DynamicDetailActivity.this).load(item.getMemberHead()).into(head);
            Glide.with(DynamicDetailActivity.this).load(dynamic.getMember().getImgUrl()).into(iv_head_small);


            if (Integer.parseInt(item.getFollow()) == 0) {
                zan.setImageResource(R.mipmap.zan_img);
                zan_tv.setText("点赞");
                zan_tv.setTextColor(Color.parseColor("#ff6a6b6e"));
            } else {
                zan.setImageResource(R.mipmap.zan_yellow);
                zan_tv.setText(item.getFollow());
                zan_tv.setTextColor(Color.parseColor("#9D9CD8"));
            }
        }
    }
}
